package com.example.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.R;
import com.example.demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经登录
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String url = req.getRequestURL().toString();
        String method = req.getMethod();
        if ("OPTIONS".equals(method)) {
            filterChain.doFilter(servletRequest,servletResponse);
        }

        if(url.contains("login") || url.contains("register")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = req.getHeader("token");

        if(!StringUtils.hasLength(token)){
            String noLogin = JSONObject.toJSONString(R.error("NO_LOGIN"));
            resp.getWriter().write(noLogin);
            return;
        }

        try{
            JWTUtils.getClaimsByToken(token);
        }catch (Exception e){
            String noLogin = JSONObject.toJSONString(R.error("NO_LOGIN"));
            resp.getWriter().write(noLogin);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
